﻿<script lang="ts" name="goodsTypeModel" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { formatDate } from '/@/utils/formatTime';
import { useGoodsTypeModelApi } from '/@/api/Goods/goodsTypeModel';

//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const goodsTypeModelApi = useGoodsTypeModelApi();
const ruleFormRef = ref();

const state = reactive({
	title: '',
	loading: false,
	showDialog: false,
	ruleForm: {} as any,
	stores: {},
	dropdownData: {} as any,
	goodsTypeTreeData: [] as any[], // 货品类型树形数据
});

// 自行添加其他规则
const rules = ref<FormRules>({
  goodsTypeCode: [{required: true, message: '请选择货品类型编码！', trigger: 'blur',},],
  goodsTypeName: [{required: true, message: '请选择货品类型名称！', trigger: 'blur',},],
  goodsTypeType: [{required: true, message: '请选择货品类型状态！', trigger: 'blur',},],
});

// 页面加载时
onMounted(async () => {
	await loadGoodsTypeList();
});

// 加载货品类型列表并构建树形结构
const loadGoodsTypeList = async () => {
	try {
		const res = await goodsTypeModelApi.page({ page: 1, pageSize: 9999 });
		const goodsTypes = res.data.result?.items || [];
		
		// 构建树形结构
		state.goodsTypeTreeData = buildTreeData(goodsTypes);
	} catch (_error) {
		console.error('加载货品类型列表失败:', _error);
	}
};

// 构建树形数据结构
const buildTreeData = (list: any[]) => {
	// 创建映射表
	const map = new Map();
	const roots: any[] = [];
	
	// 首先创建所有节点
	list.forEach(item => {
		map.set(item.id, {
			value: item.id,
			label: `${item.goodsTypeCode} - ${item.goodsTypeName}`,
			id: item.id,
			goodsParentId: item.goodsParentId,
			children: []
		});
	});
	
	// 然后建立父子关系
	list.forEach(item => {
		const node = map.get(item.id);
		if (item.goodsParentId && map.has(item.goodsParentId)) {
			// 有父节点，添加到父节点的children中
			const parent = map.get(item.goodsParentId);
			parent.children.push(node);
		} else {
			// 没有父节点或父节点不存在，作为根节点
			roots.push(node);
		}
	});
	
	// 清理空的children数组
	const cleanEmptyChildren = (nodes: any[]) => {
		nodes.forEach(node => {
			if (node.children && node.children.length === 0) {
				delete node.children;
			} else if (node.children && node.children.length > 0) {
				cleanEmptyChildren(node.children);
			}
		});
	};
	cleanEmptyChildren(roots);
	
	return roots;
};

// 自动生成货品类型编码
const generateGoodsTypeCode = async () => {
	try {
		// 获取所有货品类型数据
		const res = await goodsTypeModelApi.page({ page: 1, pageSize: 9999 });
		const goodsTypes = res.data.result?.items || [];
		
		// 找出所有以GT开头的编码
		const gtCodes = goodsTypes
			.map((item: any) => item.goodsTypeCode)
			.filter((code: string) => code && code.startsWith('GT'))
			.map((code: string) => {
				const num = parseInt(code.substring(2));
				return isNaN(num) ? 0 : num;
			});
		
		// 获取最大数字，没有则从0开始
		const maxNum = gtCodes.length > 0 ? Math.max(...gtCodes) : 0;
		
		// 生成新编码：GT + 4位数字（补零）
		const newNum = maxNum + 1;
		state.ruleForm.goodsTypeCode = 'GT' + newNum.toString().padStart(4, '0');
		
		ElMessage.success('编码生成成功');
	} catch (_error) {
		ElMessage.error('编码生成失败');
	}
};

// 打开弹窗
const openDialog = async (row: any, title: string) => {
	state.title = title;
	row = row ?? {  };
	state.ruleForm = row.id ? await goodsTypeModelApi.detail(row.id).then(res => res.data.result) : JSON.parse(JSON.stringify(row));
	
	// 新增时设置默认值
	if (!state.ruleForm.id) {
		state.ruleForm.goodsTypeType = true; // 货品类型状态默认为"是"
	}
	
	// 重新加载货品类型列表（确保数据是最新的）
	await loadGoodsTypeList();
	
	state.showDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	emit("reloadTable");
	state.showDialog = false;
};

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = state.ruleForm;
			await goodsTypeModelApi[state.ruleForm.id ? 'update' : 'add'](values);
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});
};

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
<template>
	<div class="goodsTypeModel-container">
		<el-dialog v-model="state.showDialog" :width="800" draggable :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<span>{{ state.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
					<el-form-item label="货品类型编码" prop="goodsTypeCode">
						<div style="display: flex; gap: 8px;">
							<el-input v-model="state.ruleForm.goodsTypeCode" placeholder="货品类型编码将自动生成" maxlength="64" show-word-limit readonly />
							<el-button type="primary" size="default" @click="generateGoodsTypeCode" :icon="'Refresh'">
								自动生成
							</el-button>
						</div>
					</el-form-item>
				</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="货品类型名称" prop="goodsTypeName">
							<el-input v-model="state.ruleForm.goodsTypeName" placeholder="请输入货品类型名称" maxlength="128" show-word-limit clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="货品类型状态" prop="goodsTypeType">
							<el-switch v-model="state.ruleForm.goodsTypeType" />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="货品类型备注" prop="goodsTypeNote">
							<el-input v-model="state.ruleForm.goodsTypeNote" placeholder="请输入货品类型备注" maxlength="512" show-word-limit clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="父级编号" prop="goodsParentId">
							<el-tree-select 
								v-model="state.ruleForm.goodsParentId" 
								:data="state.goodsTypeTreeData"
								placeholder="请选择父级货品类型"
								clearable
								filterable
								check-strictly
								:render-after-expand="false"
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="() => state.showDialog = false">取 消</el-button>
					<el-button @click="submit" type="primary" v-reclick="1000">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select), :deep(.el-input-number) {
  width: 100%;
}
</style>